package socket

import (
	"runtime/debug"
	"sync"
	"time"

	"qmp_go_push/pkg/logger"
	"qmp_go_push/task"

	"go.uber.org/zap"
)

// ClientManager 连接管理
type ClientManager struct {
	Users    map[string]*Client // 登录的用户
	UserLock sync.RWMutex       // 读写锁
}

// NewClientManager 创建连接管理
func NewClientManager() (clientManager *ClientManager) {
	clientManager = &ClientManager{
		Users: make(map[string]*Client),
	}
	return
}

// AddUsers 添加用户
func (manager *ClientManager) AddUsers(key string, client *Client) {
	manager.UserLock.Lock()
	defer manager.UserLock.Unlock()
	manager.Users[key] = client
}

// DelUsers 删除用户
func (manager *ClientManager) DelUsers(client *Client) (result bool) {
	manager.UserLock.Lock()
	defer manager.UserLock.Unlock()
	key := client.UserID
	if value, ok := manager.Users[key]; ok {
		if value.Addr != client.Addr {
			return
		}
		delete(manager.Users, key)
		result = true
	}
	return
}

func StartCleanConnTask() {
	task.Timer(3*time.Second, 30*time.Second, clearTimeoutConnections, "", nil, nil)
}

// clearTimeoutConnections 定时清理超时连接
func clearTimeoutConnections(param interface{}) bool {
	defer func() {
		if r := recover(); r != nil {
			logger.Error(logger.ErrLogger, "clearTimeoutConnections", zap.Any("stack", string(debug.Stack())))
		}
	}()
	currentTime := uint64(time.Now().Unix())
	for _, client := range clientManager.Users {
		if client.IsHeartbeatTimeout(currentTime) {
			_ = client.Conn.Close()
		}
	}
	return true
}
